package tungsten.base.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

/**
 * Created by Lv on 2016/6/16.
 */
public abstract class BaseClient
{
    private ChannelHandlerContext ctx;
    private MessageHandler messageHandler;

    public BaseClient(ChannelHandlerContext ctx)
    {
        this.ctx = ctx;
        this.ctx.channel().attr(AttributeKey.valueOf("Client")).set(this);
        this.messageHandler = getMessageHandler();
    }

    protected abstract MessageHandler getMessageHandler();

    public void dispose()
    {
        if(this.ctx != null)
        {
            this.ctx.channel().attr(AttributeKey.valueOf("Client")).remove();
        }
        this.ctx = null;
    }

    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(Object message)
    {
        this.ctx.writeAndFlush(messageHandler == null ? message : messageHandler.handle(message));
    }

    /**
     * 发送一系列消息
     * @param messages
     */
    public void sendMessage(Object ... messages)
    {
        for(Object message : messages)
        {
            this.ctx.write(messageHandler == null ? message : messageHandler.handle(message));
        }
        this.ctx.flush();
    }
}